#include "contacts.pb.h"
#include <iostream>
#include <fstream>

void addPersonInfo(s_contacts::PeopleInfo *info)
{
    std::cout << "----------添加新联系人----------" << std::endl;
    // 输入姓名
    std::cout << "请输入姓名: ";
    std::string name;
    std::getline(std::cin, name);
    info->set_name(name);

    // 输入年龄
    // std::cout << "请输入年龄: ";
    // int age;
    // std::cin >> age;
    // info->set_age(age);

    std::cout << "请输入薪资: ";
    int salary;
    std::cin >> salary;
    info->set_salary(salary);

    std::cin.ignore(256, '\n');

    // 输入电话
    while (1)
    {
        // 设置电话号码
        std::cout << "请输入电话号码(回车结束): ";
        std::string phone_number;
        std::getline(std::cin, phone_number);
        if (phone_number.empty())
            break;

        s_contacts::PeopleInfo_Phone *phone = info->add_phone();
        phone->set_number(phone_number);
    }

    std::cout << "----------添加联系人成功----------" << std::endl;
}

// 将通讯录的信息写入文件中
int main()
{
    // 0.先读取文件中已有的数据
    std::ifstream ifs("../contacts.bin", std::ios::in | std::ios::binary);
    s_contacts::Contacts contacts;
    if (ifs) // 检查文件是否存在，若不存在，则无需读取
        contacts.ParseFromIstream(&ifs);
    ifs.close();

    // 1.添加新的通讯人信息
    addPersonInfo(contacts.add_info());

    // 2.通讯人信息写到文件中
    std::ofstream ofs("../contacts.bin", std::ios::out | std::ios::binary | std::ios::trunc);
    if (!ofs)
    {
        std::cerr << "Failed to open file" << std::endl;
        ofs.close();
        return -1;
    }
    if (!contacts.SerializeToOstream(&ofs))
    {
        std::cerr << "Failed to write` to ostream" << std::endl;
        ofs.close();
        return -2;
    }

    ofs.close();
    return 0;
}